/**
 * File name:      LoginService.java
 * Date:           2013-3-29
 * Description:    // 用于详细说明此程序文件完成的主要功
 *                 // 能与其他模块或函数的接口，输出值、
 *                 // 取值范围、含义及参数间的关系
 * Modify History:     Date             Programmer       Notes
 *                    ---------        ---------------  ---------
 *                    2013-3-29            胡少磊                           Initial
 **********************************************************************/
package com.wy.framework.services.login;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import com.wy.business.developer.developer.services.RegistService;
import com.wy.framework.constants.Constants;
import com.wy.framework.constants.DBConstant;
import com.wy.framework.constants.RtnCodeConstant;
import com.wy.framework.dao.ErrorSqlException;
import com.wy.framework.dao.IDataBaseDao;
import com.wy.framework.exceptions.ServiceException;
import com.wy.component.ldap.LdapHelperNew;
import com.wy.component.ldap.LdapMd5;
import com.wy.framework.pojos.TSysOrginfo;
import com.wy.framework.pojos.TSysUserinfo;
import com.wy.framework.services.AbstractBaseService;
import com.wy.component.dataConvert.ConvertToJson;
import com.wy.component.dataConvert.JsonUtil;
import com.wy.component.properties.PropertiesUtil;
import com.wy.component.security.DescUtil;

/**
 * Created on 2013-3-29
 * <p>
 * Title: [用户登录]
 * </p>
 * <p>
 * Description: 用户登录相关服务
 * </p>
 * 
 * @version 1.0
 */
public class LoginService extends AbstractBaseService {

	private static Logger logger = LoggerFactory.getLogger(LoginService.class);
	static PropertiesUtil p = new PropertiesUtil();
	@Autowired
	private RegistService registService;

	/**
	 * 用户信息验证 1.用户名、密码是否错误 2.密码是否为初始密码 3.用户密码是否过期 4.用户状态 5.用户机构状态 6.用户密码输入错误次数判断
	 */
	Date d = new Date(System.currentTimeMillis()); // 年月日

	Date now = new Date();
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
	String dqsj = dateFormat.format(now);

	private JdbcTemplate jdbcTemplate;
	private HibernateDaoSupport hibernateDao;
	private IDataBaseDao dataBaseDao;

	public String validate(TSysUserinfo userInfo, String casFlag) throws ServiceException, FileNotFoundException, IOException {
		
		String source=ServletActionContext.getRequest().getParameter("source");
		try {
			if(userInfo==null)
				return RtnCodeConstant.RTN_CODE_D04_NO_EXIST_ERROR;
			String rtnCode = RtnCodeConstant.RTN_CODE_SUCCESS;
			TSysUserinfo userInfoIndb = null;
			userInfoIndb = (TSysUserinfo) this.getDataBaseDao().load(TSysUserinfo.class, userInfo.getUserId());
			
			// 1.用户不存在
			if (userInfoIndb == null) {
				return RtnCodeConstant.RTN_CODE_D04_NO_EXIST_ERROR;
			}

			// 2.判断用户以及用户机构状态
			String userState = validateUserState(userInfoIndb);
			if (userState != null) {
				return userState;
			}

			// 3. 密码输入判断 
				//浙中医大移动门户  且  非开发者平台
			if(StringUtils.equals(p.getAppProperties("projectName"), "浙中医大移动门户")){
				//admin  或者开发者平台  还是用用户表校验密码
				if(StringUtils.equals("admin", userInfo.getUserId()) || StringUtils.equals("developer", source)){
					if (!DescUtil.encrypt(userInfo.getUserPassword()).equals(userInfoIndb.getUserPassword())) {// 密码输入错误
						return RtnCodeConstant.RTN_CODE_D06_USER_ERROR;
					}
				}
				//ldap登录
				else{
					String result = LdapHelperNew.authenticate(userInfo.getUserId(),LdapMd5.Md5Encode(userInfo.getUserPassword()));
					if(StringUtils.equals(result, "false")){
						return RtnCodeConstant.RTN_CODE_D06_USER_ERROR;
					}
				}
			}
			// cas单点  不做密码校验
			else if(StringUtils.equals(casFlag, "1")){
				
			}
			//万雍移动门户
			else{
				String pass=userInfo.getUserPassword();
				String dbPass=DescUtil.decrypt(userInfoIndb.getUserPassword());
				if (!pass.trim().equals(dbPass)) {// 密码输入错误
					return RtnCodeConstant.RTN_CODE_D06_USER_ERROR;
					
				} else {
					// 4.是否初始密码
//				if (querySysConfigById(DBConstant.SYS_CONFIG_INIT_PASSWORD)
//						.equals(userInfoIndb.getUserPassword())) {
//					return RtnCodeConstant.RTN_CODE_D06_PWD_CHG_ERROR;
//				}
				}
			}
			
			//5. 角色判断
			String roleIds= getUserRole(userInfoIndb.getUserId());
			//系统管理,新闻,其他:门户
			//app管理:应用市场
			//开发者,开发者平台
			if(StringUtils.isNotEmpty(roleIds)){
				String[] arr = roleIds.split(",");
				boolean permissionFlg = false;
				for(int i=0;i<arr.length;i++){
					if(StringUtils.equals("manage", source)){
						if(!(arr[i].equals(Constants.ROLE_ADMIN) || arr[i].equals(Constants.NEWS_ADMIN) || arr[i].equals(Constants.OTHER_ADMIN) )){
							if(arr[i].equals(Constants.APP_MANAGER) || arr[i].equals(Constants.APP_DEVELOPER)){
								permissionFlg = false;
							}
							//自定义角色也可以登录移动门户,受权限菜单配置限制,只能看到某些菜单
							else{
								permissionFlg = true;
								break;
							}
						}else{
							permissionFlg = true;
							break;
						}
					}else if(StringUtils.equals("market", source)){
						if(!arr[i].equals(Constants.APP_MANAGER)){
							permissionFlg = false;
						}else{
							permissionFlg = true;
							break;
						}
					}else if(StringUtils.equals("developer", source)){
						if(!arr[i].equals(Constants.APP_DEVELOPER)){
							permissionFlg = false;
						}else{
							permissionFlg = true;
							break;
						}
					}
				}
				if(!permissionFlg){
					if(StringUtils.equals("manage", source)){
						return RtnCodeConstant.RTN_CODE_D06_USER_LOGIN_MANAGE_NOPERMISSION; 
					}else if(StringUtils.equals("market", source)){
						return RtnCodeConstant.RTN_CODE_D06_USER_LOGIN_MARKET_NOPERMISSION;
					}else if(StringUtils.equals("developer", source)){
						return RtnCodeConstant.RTN_CODE_D06_USER_LOGIN_DEVELOPER_NOPERMISSION;
					}
				}
			}
			
			userInfo.setUserId(userInfoIndb.getUserId());
			return rtnCode;
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}
	
	
	public boolean existsMobileNo(String mobileNo) {
		try {
			List params = new ArrayList();
			params.add(mobileNo);
			params.add(mobileNo);
			int i = this.dataBaseDao.queryForInt("t_sys_userinfo.ctn5",params);
			if(i > 0)
				return true;
		} catch (DataAccessException e) {
			e.printStackTrace();
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 验证用户状态以及用户所属机构状态
	 */
	public String validateUserState(TSysUserinfo userInfo)
			throws ServiceException {
		try {
			// 用户已注销
			if (DBConstant.DB_STATUS_DISABLCE.equals(userInfo.getIsAvailable())) {
				return RtnCodeConstant.RTN_CODE_D06_USER_STATE_ERROR;
			}
			// 用户已锁定
			else if (DBConstant.DB_STATUS_LOCK
					.equals(userInfo.getIsAvailable())) {
				return RtnCodeConstant.RTN_CODE_D06_USER_LOCK_ERROR;
			}
			// 机构已注销
//			String orgCode = userInfo.getDept();
//			TSysOrginfo orgInfo = null;
//			if (orgCode != null) {
//				orgInfo = (TSysOrginfo) getDataBaseDao().load(
//						TSysOrginfo.class, orgCode);
//				if (orgInfo == null || !orgInfo.validate()) {
//					return RtnCodeConstant.RTN_CODE_D06_ORG_STATE_ERROR;
//				}
//			}
			return null;
		} catch (Exception e) {
			throw new ServiceException(e);
		}

	}

	public void installTimes(String devicetype) throws ServiceException {
		try {
			dataBaseDao.update("tc_sys_installtimes.update1",devicetype);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据用户帐号查询用户信息 并补充机构名称、地区编码、角色ID
	 */
	public TSysUserinfo getUserInfo(String userAccount)
			throws ServiceException {
		try {
//			if(userAccount.trim().matches(Constants.MOBILE_PATTERN)){
//				userAccount =getUserInfoByMobileNo(userAccount).getUserId();
//			}
			TSysUserinfo userInfo = (TSysUserinfo) this.getDataBaseDao()
					.load(TSysUserinfo.class, userAccount);
			List list = dataBaseDao.getHibernateTemplate().find("select o from TSysOrginfo o,TSysUserroles ur,TSysOrgroles orgr where o.orgCode=orgr.orgCode and orgr.roleId=ur.roleId and ur.userId=?  ", new Object[]{userInfo.getUserId()});
			if(list!=null && list.size()>0){
				TSysOrginfo orgInfo = (TSysOrginfo) list.get(0);
				if (orgInfo!=null) {
					userInfo.setDept(orgInfo.getOrgName());
					userInfo.setDeptName(orgInfo.getOrgName());
				}
			}
			return userInfo;
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 
	 * Function Name               getUserInfoDetail                                   
	 * @param userAccount
	 * @return
	 * @throws Exception          		             
	 * @description 得到用户信息
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-5-4 下午5:48:50           黄忠                     Initial
	 **********************************************************************
	 */
	public TSysUserinfo getUserInfoDetail(String userAccount) throws Exception {
		return (TSysUserinfo) this.getDataBaseDao().load(TSysUserinfo.class, userAccount);
	} 

//	@SuppressWarnings({ "rawtypes", "unchecked" })
//	public String register(String name, String mobile, String email,
//			String unit, String position, String pwd, String currentRoot,
//			String confferenceId, String openId) throws ServiceException {
//		// 万雍销售4部客户引流到万雍科技渠道
//		// if(StringUtils.equals("bd387b03-facb-4328-b586-dcfb56213d0b",
//		// currentRoot) && StringUtils.equals(confferenceId,
//		// "3D01B621-FEDE-42C1-9515-17E1E58792B5")){
//		// currentRoot = "f5433a22-46ee-45d0-9640-e756c1fbc463";
//		// }
//		try {
//			// 密码传进来
//			String pwd1 ="";
//			if(StringUtils.isNotEmpty(pwd)){
//				pwd1= DescUtil.encrypt(pwd);// 加密以后的密码
//			}
//			else{
//				pwd1= DescUtil.encrypt(mobile.substring(5, mobile.length()));// 加密以后的密码
//			}
//			if (StringUtils.isEmpty(confferenceId)) {
//				TcSysUserInfo tcSysUserInfo = new TcSysUserInfo();
//				tcSysUserInfo.setUserId(UUID.randomUUID().toString());
//				tcSysUserInfo.setMobileNo(mobile);
//				// 二维码
////				String qrcode = "{\"id\":\"" + tcSysUserInfo.getUserId()
////						+ "\",\"type\":\"user\"} ";
////				String path = this.getClass().getClassLoader().getResource("/")
////						.getPath().replace("/WEB-INF/classes", "")
////						+ "/qrcode"; // 真实路径
////				tcSysUserInfo.setQrcode("qrcode/"
////						+ GenerateQRcodeUtil.createImage(qrcode,
////								tcSysUserInfo.getUserId(), path));
//				tcSysUserInfo.setIsAvailable("1");
//				tcSysUserInfo.setOutFlag("0");
//				tcSysUserInfo.setRoleId(new CommonUtil().getAppProperties("ROLE_YB_USER"));
//				tcSysUserInfo.setEmail(email);
//				// 密码传进来
//				tcSysUserInfo.setUserPassword(pwd1);
//				tcSysUserInfo.flushUpdateTime();
//				tcSysUserInfo.setUserName(name);
//				tcSysUserInfo.setPosition(position);
//				tcSysUserInfo.setRegisterSource(Constants.Reg_From_WeChat);// 注册来源
//				tcSysUserInfo.setOpenId(openId);
//				tcSysUserInfo.setCreateTime(new Date());
//				tcSysUserInfo.setState(Constants.VERIFY_PASS);
//				tcSysUserInfo.setManageFlag("0");
//				tcSysUserInfo.setUnit(unit);
//				// 新注册用户设置默认头像
//				int number = new Random().nextInt(12) + 1;
//				URL url = this.getClass().getClassLoader().getResource("/");
//				String pathRoot = url.getPath().replace("/WEB-INF/classes", ""); // 真实路径
//				String sourceimgName = number + ".png";
//				String Source = pathRoot + "/template/defaultheadimg/"
//						+ sourceimgName;
//				String targetimgName = "headImg_"
//						+ tcSysUserInfo.getUserId() + ".jpg";
//				String target = pathRoot + "/upload/" + targetimgName;
//				CommonUtil.copyFile(new File(Source), new File(target));
//
//				getHibernateDao().getHibernateTemplate().saveOrUpdate(
//						tcSysUserInfo);
//				TcSysUserRoles userRoles = new TcSysUserRoles();
//				userRoles.setRoleId(tcSysUserInfo.getRoleId());
//				userRoles.setUserId(tcSysUserInfo.getUserId());
//				userRoles.setUserRoleId(UUID.randomUUID().toString());
//				userRoles.setIsAvailable(DBConstant.DB_STATUS_ABLCE);
//				userRoles.flushUpdateTime();
//				getHibernateDao().getHibernateTemplate().save(userRoles);
//			} else {
//				// 根据活动创建人取2级组织码
//				TbConfferenceBaseinfo tbConfferenceBaseinfo = (TbConfferenceBaseinfo) this.dataBaseDao
//						.load(TbConfferenceBaseinfo.class, confferenceId);
//				if (StringUtils.isEmpty(currentRoot)) {
//					currentRoot = this.getCurrentRoot(null,
//							tbConfferenceBaseinfo.getUserId());
//				}
//				// 校验密码
//				List params = new ArrayList();
//				params.add(mobile);
//				int i = this.dataBaseDao.queryForInt("t_sys_userinfo.ctn6",params);
//				if (i > 0) {
//					params = new ArrayList();
//					params.add(mobile);
//					params.add(DescUtil.encrypt(pwd));
//					i = this.dataBaseDao.queryForInt("t_sys_userinfo.ctn7",params);
//					if (i <= 0) {
//						return "该账号密码校验失败，请重新输入！";
//					}
//				}
//				TcSysUserInfo tcSysUserInfoDb = (TcSysUserInfo) this.dataBaseDao
//						.load(TcSysUserInfo.class, mobile);
//				if (tcSysUserInfoDb == null) {
//					TcSysUserInfo tcSysUserInfo = new TcSysUserInfo();
//					tcSysUserInfo.setUserId(UUID.randomUUID().toString());
//					tcSysUserInfo.setMobileNo(mobile);
//					// 二维码
////					String qrcode = "{\"id\":\""
////							+ tcSysUserInfo.getUserId()
////							+ "\",\"type\":\"user\"} ";
////					String path = this.getClass().getClassLoader()
////							.getResource("/").getPath()
////							.replace("/WEB-INF/classes", "")
////							+ "/qrcode"; // 真实路径
////					tcSysUserInfo.setQrcode("qrcode/"
////							+ GenerateQRcodeUtil.createImage(qrcode,
////									tcSysUserInfo.getUserId(), path));
//					tcSysUserInfo.setIsAvailable("1");
//					tcSysUserInfo.setOutFlag("0");
//					tcSysUserInfo.setRoleId(new CommonUtil().getAppProperties("ROLE_YB_USER"));
//					tcSysUserInfo.setEmail(email);
//					tcSysUserInfo.setUserPassword(pwd1);
//					tcSysUserInfo.flushUpdateTime();
//					tcSysUserInfo.setUserName(name);
//					tcSysUserInfo.setPosition(position);
//					tcSysUserInfo.setRegisterSource(Constants.Reg_From_Detail);// 注册来源
//					tcSysUserInfo.setCreateTime(new Date());
//					// 修改部门 找到当前学校其它这个部门
//					params = new ArrayList();
//					params.add(currentRoot);
//					List list = this.dataBaseDao.queryForList("tc_sys_orginfo.orgCode",params);
//					String orgCode = (String) ((list == null
//							|| list.size() == 0 || list.get(0) == null) ? ""
//							: ((Map) list.get(0)).get("orgCode"));
//					tcSysUserInfo.setDept(orgCode);
//					tcSysUserInfo.setState(Constants.VERIFY_PASS);
//					tcSysUserInfo.setManageFlag("0");
//					tcSysUserInfo.setUnit(unit);
//					// 新注册用户设置默认头像
//					int number = new Random().nextInt(12) + 1;
//					URL url = this.getClass().getClassLoader().getResource("/");
//					String pathRoot = url.getPath().replace("/WEB-INF/classes",
//							""); // 真实路径
//					String sourceimgName = number + ".png";
//					String Source = pathRoot + "/template/defaultheadimg/"
//							+ sourceimgName;
//					String targetimgName = "headImg_"
//							+ tcSysUserInfo.getUserId() + ".jpg";
//					String target = pathRoot + "/upload/" + targetimgName;
//					CommonUtil.copyFile(new File(Source), new File(target));
//
//					getHibernateDao().getHibernateTemplate().saveOrUpdate(
//							tcSysUserInfo);
//					if(StringUtils.isEmpty(pwd)){
//						//发送默认手机密码短信
//						sendVerificationCodeService.sendMessageForRegister(mobile, confferenceId);
//					}
//					TcSysUserRoles userRoles = new TcSysUserRoles();
//					userRoles.setRoleId(tcSysUserInfo.getRoleId());
//					userRoles.setUserId(tcSysUserInfo.getUserId());
//					userRoles.setUserRoleId(UUID.randomUUID().toString());
//					userRoles.setIsAvailable(DBConstant.DB_STATUS_ABLCE);
//					userRoles.flushUpdateTime();
//					getHibernateDao().getHibernateTemplate().save(userRoles);
//				}
//			}
//
//			return "0";
//		} catch (Exception e) {
//			e.printStackTrace();
//			return "0";
//		}
//	}

	/**
	 * 用户注册
	 * 
	 * @param name
	 * @param mobile
	 * @param position
	 * @param email
	 * @param pwd
	 * @param unit
	 * @return
	 * @throws ServiceException
	 */
//	@SuppressWarnings("rawtypes")
//	public String Appregister(String name, String mobile, String position,
//			String email, String pwd, String unit) throws ServiceException {
//		String sql = null;
//		String deviceType = ServletActionContext.getRequest().getParameter("deviceType");
//		try {
//			List params = new ArrayList();
//			params.add(mobile);
//			List<Map> list = dataBaseDao.queryForList("t_sys_userinfo.list1", params);
//			if (list.size() == 0) {
//				TSysUserinfo tcSysUserInfo = new TSysUserinfo();
//				tcSysUserInfo.setUserId(UUID.randomUUID().toString());
//				// 二维码
////				String qrcode = "{\"id\":\"" + tcSysUserInfo.getUserId()
////						+ "\",\"type\":\"user\"} ";
////				String path = this.getClass().getClassLoader().getResource("/")
////						.getPath().replace("/WEB-INF/classes", "")
////						+ "/qrcode"; // 真实路径
////				tcSysUserInfo.setQrcode("qrcode/"
////						+ GenerateQRcodeUtil.createImage(qrcode,
////								tcSysUserInfo.getUserId(), path));
//				tcSysUserInfo.setIsAvailable("1");
//				tcSysUserInfo.setOutFlag("0");
//				tcSysUserInfo.setRoleId(new CommonUtil().getAppProperties("ROLE_YB_USER"));
//				// 密码传进来
//				String pwd1 = DescUtil.encrypt(pwd);// 加密以后的密码
//				tcSysUserInfo.setUserPassword(pwd1);
//				tcSysUserInfo.flushUpdateTime();
//				tcSysUserInfo.setUserName(name);
//				tcSysUserInfo.setDept("");// 挂在根节点
//				tcSysUserInfo.setPosition(position);
//				tcSysUserInfo.setMobileNo(mobile);
//				tcSysUserInfo.setEmail(email);
//				tcSysUserInfo.setUnit(unit);
//				tcSysUserInfo.setManageFlag("0");
//				tcSysUserInfo.setRegisterSource(Constants.Reg_From_App);// 注册来源
//				tcSysUserInfo.setCreateTime(new Date());
////				TbConfferenceApply tbConfferenceApply = new TbConfferenceApply();
////				tbConfferenceApply.setApplyId(UUID.randomUUID().toString());
////				tbConfferenceApply.setIsAvailable("1");
////				tbConfferenceApply.setStatus(Constants.VERIFY_PASS);
////				// tbConfferenceApply.setStatus(Constants.VERIFY_PERFECT);
////				tbConfferenceApply.setUserId(tcSysUserInfo.getUserId());
////				tbConfferenceApply.setUpdateTime(new Timestamp(System
////						.currentTimeMillis()));
////				getHibernateDao().getHibernateTemplate().save(
////						tbConfferenceApply);
//
//				tcSysUserInfo.setState(Constants.VERIFY_PASS);
//				// tcSysUserInfo.setState(Constants.VERIFY_PERFECT);
//
//				// 新注册用户设置默认头像
//				int number = new Random().nextInt(12) + 1;
//				URL url = this.getClass().getClassLoader().getResource("/");
//				String pathRoot = url.getPath().replace("/WEB-INF/classes", ""); // 真实路径
//				String sourceimgName = number + ".png";
//				String Source = pathRoot + "/template/defaultheadimg/"
//						+ sourceimgName;
//				String targetimgName = "headImg_"
//						+ tcSysUserInfo.getUserId() + ".jpg";
//				String target = pathRoot + "/upload/" + targetimgName;
//				CommonUtil.copyFile(new File(Source), new File(target));
//
//				getHibernateDao().getHibernateTemplate().save(tcSysUserInfo);
//
//				TSysUserRoles userRoles = new TSysUserRoles();
//				userRoles.setRoleId(tcSysUserInfo.getRoleId());
//				userRoles.setUserId(tcSysUserInfo.getUserId());
//				userRoles.setUserRoleId(UUID.randomUUID().toString());
//				userRoles.setIsAvailable(DBConstant.DB_STATUS_ABLCE);
//				userRoles.flushUpdateTime();
//				getHibernateDao().getHibernateTemplate().save(userRoles);
//				
//				//注册次数
//				params = new ArrayList();
//				params.add(deviceType);
//				dataBaseDao.update("tc_sys_installtimes.update",params);
//				return "0";// 不存在
//			} else {
//				return "1";// 手机号存在
//			}
//
//		} catch (Exception e) {
//			e.printStackTrace();
//			return "0";
//		}
//	}

	/**
	 * 加载用户权限对应Action
	 */
	@SuppressWarnings("rawtypes")
	public Set<String> getUserAction(TSysUserinfo userInfo)
			throws ServiceException {
		try {
			Set<String> actionSet = new HashSet<String>();
			// 查询用户拥有的功能
			List<Map> actionsList = this.getDataBaseDao()
					.queryForList("t_sys_function.queryActionByRoleId",
							userInfo.getUserId());
			for (Map map : actionsList) {
				String availableUri = (String) map.get("availableURI");
				if (availableUri != null && availableUri.trim().length() > 0) {
					String[] actions = availableUri.split(",");
					for (String action : actions) {
						actionSet.add(action);
					}
				}
			}
			return actionSet;
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}

	private String getUserRole(String userAccount) throws ServiceException {
		try {
			List<Map> result = this.getDataBaseDao().queryForList(
					"t_sys_userroles.queryRoleIdByUser", userAccount);
			if (result.size() > 0) {
				return (String) result.get(0).get("roleIds");
			}
			return null;
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String userLogin(String userAccount, String passWord, boolean smsLoginFlg) throws ErrorSqlException {
		//是否手机号登录
		if(userAccount.matches(Constants.MOBILE_PATTERN)){
			TSysUserinfo tcSysUserInfo = getUserInfoByMobileNo(userAccount);
			if(tcSysUserInfo == null)
				return "{\"msg\":{\"message\":\"账号不存在\"},\"res\":\"false\"}";
			else
				userAccount = tcSysUserInfo.getUserId();
		}
		
		List params = new ArrayList();
		params.add(userAccount);
		params.add("SYS_ADMIN");
		int i = this.dataBaseDao.queryForInt("tc_sys_userroles.ctn",params);
		if (i > 0) {
			return "{\"msg\":{\"message\":\"超级管理员禁止登录，请用其它账号登录！\"},\"res\":\"false\"}";
		}
		
		String openId = ServletActionContext.getRequest().getParameter("openId");
		if (StringUtils.isNotEmpty(openId)) {
			params = new ArrayList();
			params.add(userAccount);
			List list = this.dataBaseDao.queryForList("t_sys_userinfo.openId");
			String openIdDb = (String) ((list == null || list.size() == 0 || list
					.get(0) == null) ? "" : ((Map) list.get(0)).get("openId"));
			if (StringUtils.isNotEmpty(openIdDb)) {
				return "{\"msg\":{\"message\":\"登录失败,该账号已绑定其它微信号!\"},\"res\":\"false\"}";
			}
//			TSysUserinfo tcSysUserInfo = (TSysUserinfo) this.dataBaseDao.load(TSysUserinfo.class, userAccount);
//			tcSysUserInfo.setOpenId(openId);
//			this.dataBaseDao.update(tcSysUserInfo);
		}
		
		//短信验证登录流程
		String passwordSql = "";
		if(!smsLoginFlg){
			passwordSql = " AND a.`userPassword`='"+passWord+"' ";
		}
		params = new ArrayList();
		params.add(userAccount);
		params.add(userAccount);
		List<Map> list = this.dataBaseDao.queryForList("t_sys_userinfo.something3", params,passwordSql);
		if (list != null && list.size() > 0) {
			return ConvertToJson.List2Json(list, true);
		} else {
			params = new ArrayList();
			params.add(userAccount);
			List list2 = this.dataBaseDao.queryForList("t_sys_userinfo.headImg", params);
			if (list2 != null && list2.size() > 0) {
				return "{\"msg\":{\"message\":\"请输入正确的登录密码\"},\"res\":\"false\"}";
			} else {
				return "{\"msg\":{\"message\":\"账号不存在\"},\"res\":\"false\"}";
			}
		}
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String userLogin_V1_1(String userAccount, String passWord, boolean smsLoginFlg) throws ErrorSqlException {
		//是否手机号登录
		if(userAccount.matches(Constants.MOBILE_PATTERN)){
			TSysUserinfo tcSysUserInfo = getUserInfoByMobileNo(userAccount);
			if(tcSysUserInfo == null)
				return "{\"msg\":{\"message\":\"账号不存在\"},\"res\":\"false\"}";
			else
				userAccount = tcSysUserInfo.getUserId();
		}
		
		List params = new ArrayList();
		params.add(userAccount);
		params.add("SYS_ADMIN");
		int i = this.dataBaseDao.queryForInt("tc_sys_userroles.ctn",params);
		if (i > 0) {
			return "{\"msg\":{\"message\":\"超级管理员禁止登录，请用其它账号登录！\"},\"res\":\"false\"}";
		}
		
		String openId = ServletActionContext.getRequest().getParameter("openId");
		if (StringUtils.isNotEmpty(openId)) {
			params = new ArrayList();
			params.add(userAccount);
			List list = this.dataBaseDao.queryForList("t_sys_userinfo.openId",params);
			String openIdDb = (String) ((list == null || list.size() == 0 || list
					.get(0) == null) ? "" : ((Map) list.get(0)).get("openId"));
			if (StringUtils.isNotEmpty(openIdDb)) {
				return "{\"msg\":{\"message\":\"登录失败,该账号已绑定其它微信号!\"},\"res\":\"false\"}";
			}
//			TSysUserinfo tcSysUserInfo = (TSysUserinfo) this.dataBaseDao.load(TSysUserinfo.class, userAccount);
//			tcSysUserInfo.setOpenId(openId);
//			this.dataBaseDao.update(tcSysUserInfo);
		}
		
		//短信验证登录流程
		String passwordSql = "";
		if(!smsLoginFlg){
			passwordSql = " AND a.`userPassword`='"+passWord+"' ";
		}
		StringBuffer sql = new StringBuffer();
		params = new ArrayList();
		params.add(userAccount);
		params.add(userAccount);
		List<Map> list = this.dataBaseDao.queryForList("t_sys_userinfo.something4", params,passwordSql);
		if (list != null && list.size() > 0) {
			return ConvertToJson.List2Json(list, true);
		} else {
			params = new ArrayList();
			params.add(userAccount);
			List list2 = this.dataBaseDao.queryForList("t_sys_userinfo.headImg",params);
			if (list2 != null && list2.size() > 0) {
				return "{\"msg\":{\"message\":\"请输入正确的登录密码\"},\"res\":\"false\"}";
			} else {
				return "{\"msg\":{\"message\":\"账号不存在\"},\"res\":\"false\"}";
			}
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List getlogUserModule(String userAccount, String confferenceId)
			throws ErrorSqlException {
		List params = new ArrayList();
		params.add(confferenceId);
		params.add(userAccount);
		params.add(confferenceId);
		params.add(userAccount);
		params.add(confferenceId);
		params.add(confferenceId);
		params.add(confferenceId);
		params.add(userAccount);
		params.add(confferenceId);
		params.add(confferenceId);
		params.add(confferenceId);
		params.add(confferenceId);
		params.add(userAccount);
		params.add(confferenceId);
		params.add(confferenceId);
		return this.dataBaseDao.queryForList("tb_confference_model.getlogUserModule", params);
	}

	public String getLoginUserRight(String userAccount, String confferenceId, String modelId)
			throws ErrorSqlException {
		// 查看登陆用户权限，判断android问卷开关是否显示
		String isManage = "0";
		TSysUserinfo logUserInfo = (TSysUserinfo) this.dataBaseDao.load(
				TSysUserinfo.class, userAccount);
		if (logUserInfo == null)
			return "0";
		List revokeList = new ArrayList();
		List params = new ArrayList();
		params.add(userAccount);
		List listRoleIds = this.dataBaseDao.queryForList("tc_sys_userroles.roleId",params);
		String roleId = (String) ((listRoleIds == null
				|| listRoleIds.size() == 0 || listRoleIds.get(0) == null) ? ""
				: ((Map) listRoleIds.get(0)).get("roleId"));

		// 一级超管及二级超管
		if (StringUtils.equals(userAccount, "admin")
				|| StringUtils.equals(roleId, Constants.ROLE_ADMIN)) {
			isManage = "1";
		}
		// 其他用户
		else {
			if (confferenceId != null && confferenceId != "") {
				params = new ArrayList();
				params.add(userAccount);
				params.add(confferenceId);
				int createUserMeeting = this.dataBaseDao.queryForInt("tb_confference_baseinfo.ctn1",params);
				params = new ArrayList();
				params.add(confferenceId);
				params.add(userAccount);
				params.add(modelId);
				revokeList = this.dataBaseDao.queryForList("tb_confference_rostermapmodel.list", params);
				if (createUserMeeting > 0 || revokeList.size() > 0 || StringUtils.equals(userAccount, Constants.ADMIN_LEVEL)) {
					isManage = "1";
				} else {
					isManage = "0";
				}
			} else {// 应用问卷
				isManage = "0";
			}
		}
		return isManage;
	}

	public List checkUserInfo(String mobile) throws DataAccessException,
			ErrorSqlException {
		// 根据手机号验证账户是否存在
		StringBuffer sb = new StringBuffer(" from TcSysUserInfo where 1=1 and mobileNo=?");
		List list = dataBaseDao.getHibernateTemplate().find(sb.toString(),mobile);
		return list;

	}

	// 修改账户密码
	public String updateUserInfo(TSysUserinfo userInfo)
			throws DataAccessException, ErrorSqlException {
		StringBuffer sb = new StringBuffer(" from TcSysUserInfo u where 1=1 ");
		sb.append(" and (u.userAccount=? or u.mobileNo=? )");
		TSysUserinfo tu = (TSysUserinfo) dataBaseDao.getHibernateTemplate().find(sb.toString(),new Object[]{userInfo.getUserId(),userInfo.getUserId()}).get(0);
		tu.setUserPassword(DescUtil.encrypt(userInfo.getUserPassword()));
		dataBaseDao.update(tu);
		return RtnCodeConstant.RTN_CODE_SUCCESS;
	}

//	// 查询微信用户信息
//	@SuppressWarnings("unchecked")
//	public List<Map> getWXUserLogin(String openId) throws ErrorSqlException,
//			FileNotFoundException, IOException {
//		StringBuffer sql = new StringBuffer();
//
//		List params = new ArrayList();
//		params.add(openId);
//		params.add(openId);
//		List<Map> list = this.dataBaseDao.queryForList("t_sys_userinfo.something6",params);
//		if (list != null && list.size() > 0) {
//			String result = ImageUtil.getWxUserInfo(openId);// 根据openId取微信个人信息
//			JSONObject j = new JSONObject(result);
//			list.get(0).put("headImg", j.get("headimgurl"));// 设置微信头像
//			String mobileNo = list.get(0).get("mobileNo") == null ? "" : list
//					.get(0).get("mobileNo").toString();
//			if (mobileNo == "") {
//				list.get(0).put("mobileNo", "待完善");
//			}
//			String position = list.get(0).get("position") == null ? "" : list
//					.get(0).get("position").toString();
//			if (position == "") {
//				list.get(0).put("position", "待完善");
//			}
//			String stationName = list.get(0).get("stationName") == null ? ""
//					: list.get(0).get("stationName").toString();
//			if (stationName == "") {
//				list.get(0).put("stationName", "待完善");
//			}
//			String identifyNo = list.get(0).get("identifyNo") == null ? ""
//					: list.get(0).get("identifyNo").toString();
//			if (identifyNo != ""
//					&& (identifyNo.length() == 15 || identifyNo.length() == 18)) {
//				list.get(0).put("age", ImageUtil.getAgeByIdCode(identifyNo));
//				list.get(0).put("sex", ImageUtil.getSexByIdCode(identifyNo));
//			} else {
//				String sex = list.get(0).get("sex") == null ? "" : list.get(0)
//						.get("sex").toString();
//				String age = list.get(0).get("age") == null ? "" : list.get(0)
//						.get("age").toString();
//				if (StringUtils.equals(sex, "1")) {
//					list.get(0).put("sex", "男");
//				} else if (StringUtils.equals(sex, "0")) {
//					list.get(0).put("sex", "女");
//				} else {
//					list.get(0).put("sex", "未知");
//				}
//				if (age != "") {
//					list.get(0).put("age", age);
//				} else {
//					list.get(0).put("age", "未知");
//				}
//			}
//		}
//		return list;
//	}

	// 修改微信用户个人资料
//	@SuppressWarnings("rawtypes")
//	public String updateWXUserInfo(TSysUserinfo tcSysUserInfo)
//			throws ErrorSqlException, ServiceException {
//		List list = dataBaseDao.getHibernateTemplate().find(
//				" from TcSysUserInfo where openId=?",tcSysUserInfo.getOpenId());
//		if (list != null && list.size() > 0 && list.get(0) != null) {
//			TSysUserinfo tc = (TSysUserinfo) list.get(0);
//			tc.setIdentifyNo(tcSysUserInfo.getIdentifyNo());
//			dataBaseDao.getHibernateTemplate().update(tc);
//			return RtnCodeConstant.RTN_CODE_SUCCESS;
//		}
//		return RtnCodeConstant.RTN_CODE_NO_EXIST_ERROR;
//	}

//	// 查询微信用户二维码
//	@SuppressWarnings({ "rawtypes", "unchecked" })
//	public List queryQrCodeForWxUser(String openId) throws ErrorSqlException,
//			FileNotFoundException, IOException {
//		List params = new ArrayList();
//		params.add(openId);
//		List<Map> list = dataBaseDao.queryForList("t_sys_userinfo.something5", params);
//		String result = ImageUtil.getWxUserInfo(openId);// 根据openId取微信个人信息
//		JSONObject j = new JSONObject(result);
//		list.get(0).put("headImg", j.get("headimgurl"));// 设置微信头像
//		return list;
//	}

//	// 查询微信用户资料
//	@SuppressWarnings({ "rawtypes", "unchecked" })
//	public List queryWXUser(String openId) throws ErrorSqlException,
//			FileNotFoundException, IOException {
//		List params = new ArrayList();
//		params.add(openId);
//		List<Map> list = dataBaseDao.queryForList("tb_confference_roster.something", params);
//		String result = ImageUtil.getWxUserInfo(openId);// 根据openId取微信个人信息
//		JSONObject j = new JSONObject(result);
//		list.get(0).put("headImg", j.get("headimgurl"));// 设置微信头像
//		return list;
//	}

	public TSysUserinfo queryWxUserByOpenId(String openId)
			throws DataAccessException, ErrorSqlException {
		String sql = " from TcSysUserInfo t where t.openId=?";
		return (TSysUserinfo) dataBaseDao.getHibernateTemplate().find(sql,openId);
	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public HibernateDaoSupport getHibernateDao() {
		return hibernateDao;
	}

	public void setHibernateDao(HibernateDaoSupport hibernateDao) {
		this.hibernateDao = hibernateDao;
	}

	public IDataBaseDao getDataBaseDao() {
		return dataBaseDao;
	}

	public void setDataBaseDao(IDataBaseDao dataBaseDao) {
		this.dataBaseDao = dataBaseDao;
	}


	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String getChildidList(String orgCode) throws DataAccessException,
			ErrorSqlException {
		List params = new ArrayList();
		params.add(orgCode);
		List<Map> mapList = dataBaseDao.queryForList("getChildidList",params);
		return (String) mapList.get(0).get("getChildidList");

	}

	public String getUserId(String openId) {
		try {
			List<Map> userInfoList;
			List params = new ArrayList();
			params.add(openId);
			userInfoList = dataBaseDao.queryForList("t_sys_userinfo.list2", params);
			String userAccount = userInfoList.get(0).get("userAccount")
					.toString();
			return userAccount;
		} catch (ErrorSqlException e) {
			e.printStackTrace();
			return null;
		}
	}

	public TSysUserinfo getUserInfoByMobileNo(String mobileNo) {
		TSysUserinfo tcSysUserInfo = null;
		List list;
		try {
			list = this.getDataBaseDao().getHibernateTemplate().find("from TcSysUserInfo where mobileNo = ?",mobileNo);
			if(list!=null && list.size()>0)
				tcSysUserInfo = (TSysUserinfo) list.get(0);
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
		return tcSysUserInfo;
	}
	
	@SuppressWarnings("rawtypes")
	public String getCurrentRoot(String orgCode, String userAccount)
			throws DataAccessException, ErrorSqlException {
		// 该用户不存在机构的情况
		boolean orgCodeNullFlg = false;
		// 只传userAccount的情况,取orgCode
		if (StringUtils.isEmpty(orgCode) && StringUtils.isNotEmpty(userAccount)) {
			List params = new ArrayList();
			params.add(userAccount);
			List list = this.dataBaseDao.queryForList(
					"t_sys_userinfo.orgCode",params);
			orgCode = (String) ((list == null || list.size() == 0 || list
					.get(0) == null) ? "" : ((Map) list.get(0)).get("orgCode"));
		}

		if (StringUtils.isEmpty(orgCode)) {
			orgCodeNullFlg = true;
		}

		// 这个while是为了递归取2级节点
		String parentDept = orgCode, currentRoot = "";
		while (!StringUtils.equals(parentDept, "000000")
				&& StringUtils.isNotEmpty(parentDept)) {
			currentRoot = parentDept;
			List params = new ArrayList();
			params.add(parentDept);
			List list = this.dataBaseDao.queryForList(
					"tc_sys_orginfo.parentDept",params);
			parentDept = (String) ((list == null || list.size() == 0 || list
					.get(0) == null) ? "" : ((Map) list.get(0))
					.get("parentDept"));
		}

		// 如果2级节点空 且 为admin登陆则赋予000000 或 传入的orgCode参数直接就是000000 或
		// 该用户不存在机构时赋予000000
		if (StringUtils.isEmpty(currentRoot)
				&& (StringUtils.equals(userAccount, "admin") || StringUtils
						.equals(orgCode, Constants.ORG_CODE_ROOT))
				|| orgCodeNullFlg) {
			currentRoot = "000000";
		}
		return currentRoot;
	}
	
	//根据地区编号查询地区信息
	public String getArea(String districtCode) throws ErrorSqlException{
		String districtName="";
		while(!org.apache.commons.lang.StringUtils.equals(districtCode, "CN") && org.apache.commons.lang.StringUtils.isNotBlank(districtCode)){
			List<Map> listMap= dataBaseDao.queryForList("TcSysUserInfo.getArea", districtCode);
			if(listMap!=null && listMap.size()>0 && listMap.get(0)!=null){
				String dName=(String) listMap.get(0).get("districtName");
				districtCode=(String) listMap.get(0).get("parentDistrictCode");
				districtName=dName+" "+districtName;
			}
			else{
				break;
			}
		}
		return districtName;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String getMenuData(TSysUserinfo loginUser) {
		try {
			List list = dataBaseDao.queryForList("t_sys_function.queryByUserId", loginUser.getUserId());
			List results = new ArrayList();
			Map allMenu = new HashMap();
			for(Object obj : list){
				Map menu = (Map)obj;
				allMenu.put(menu.get("functionId"), menu);
			}
			//遍历所有menu
			Set<Map.Entry> set = allMenu.entrySet();
			for (Iterator<Map.Entry> it = set.iterator(); it.hasNext();) {
				Map.Entry entry = (Map.Entry) it.next();
				Map menu = (Map) entry.getValue();
				String parentFunctionId = menu.get("parentFunctionId")==null?"":menu.get("parentFunctionId").toString();
				//当前为子菜单时,加入父菜单子集
				if(StringUtils.isNotEmpty(parentFunctionId)){
					Map fatherMenu = (Map) allMenu.get(parentFunctionId);
					List childs = (List) fatherMenu.get("childs");
					if(childs == null){
						childs = new ArrayList();
						fatherMenu.put("childs", childs);
					}
					childs.add(menu);
					//排序
					Collections.sort(childs,new Comparator(){
					  @Override
					  public int compare(Object o1, Object o2) {
//						  System.out.println(((BigDecimal)((Map)o1).get("priority"))+" vs " + (BigDecimal)((Map)o2).get("priority") + " result " + ((BigDecimal)((Map)o1).get("priority")).compareTo((BigDecimal)((Map)o2).get("priority")));
					    return ((BigDecimal)((Map)o1).get("priority")).compareTo((BigDecimal)((Map)o2).get("priority"));
					  }
					});
				}else
					results.add(menu);
			}
			//排序
			Collections.sort(results,new Comparator(){
			  @Override
			  public int compare(Object o1, Object o2) {
//				  System.out.println(((BigDecimal)((Map)o1).get("priority"))+" vs " + (BigDecimal)((Map)o2).get("priority") + " result " + ((BigDecimal)((Map)o1).get("priority")).compareTo((BigDecimal)((Map)o2).get("priority")));
			    return ((BigDecimal)((Map)o1).get("priority")).compareTo((BigDecimal)((Map)o2).get("priority"));
			  }
			});
			return JsonUtil.list2json(results);
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		return JsonUtil.list2json(new ArrayList());
	}
	
}
